/*
 * 同步产品税率
 */
@RestResource(urlMapping='/CRM/upsertSaletaxREST/*')
global without sharing class UpsertSaleTaxREST
{
    @HttpPost()
    global static RestReturnMessage upsertSaletax(List<SaleRestArgs> data)
    {
        RestReturnMessage message = null;
        try{
            if(data.size() > 0){
                message = doUpsertSaleTax(data);
            }else{
                throw new DmlException('没有数据');
            }
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** 错误信息: ' + e.getMessage() );
            System.debug(LoggingLevel.INFO, '*** 错误跟踪: ' + e.getStackTraceString());
            message = Utils.getRestReturnMessage(false,e.getMessage() + ' - ' + e.getStackTraceString()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());
        }
        System.debug(LoggingLevel.INFO, '*** 调用返回信息: ' + message);
        return message;
    }
     public static Map<String, String> getPicklistValues(String sObjectName, String sFieldName){

        Map<String, String> picValues= new Map<String, String>();
        Map<String, Schema.SObjectType> sObjectDescribeMap = Schema.getGlobalDescribe();
        if (sObjectDescribeMap.containsKey(sObjectName)) {
            Map<String, Schema.SobjectField> sObjectFieldsMap = 
               sObjectDescribeMap.get(sObjectName).getDescribe().fields.getMap();
            if (sObjectFieldsMap.containsKey(sFieldName)) {
                Schema.DescribeFieldResult sObjectFieldDescribe = sObjectFieldsMap.get(sFieldName).getDescribe();
                List<Schema.PicklistEntry> lPickEntryList = sObjectFieldDescribe.getPicklistValues();
                for (Schema.PicklistEntry tPicklistEntry : lPickEntryList) {
                    if(tPicklistEntry.isActive() == true){
                        picValues.put(tPicklistEntry.getValue(),tPicklistEntry.getLabel());
                    }
                 
                }
            }
        } 
        return picValues;
    }
    global static RestReturnMessage doUpsertSaleTax(List<SaleRestArgs> data){
         RestReturnMessage message = null;
        ///获取公司 和公司编码的对应关系
        Map<String,String> corpcodeMap= new Map<String,String>();
        corpcodeMap = getPicklistValues('Contract__c','Corpcode__c');
        System.debug(corpcodeMap);
        /// 产品的pk
        Set<String> productSets = new Set<String>();
        for (SaleRestArgs st : data) {
            ///如果发现有新的公司 立马报错 去维护
            if(!corpcodeMap.containsKey(st.unitcode)){
                String msg = '税率同步发现NC传来新的公司,公司编码为:' + st.unitcode;
                message = Utils.getRestReturnMessage(false,msg,new List<Map<String ,String>>());
                return message;
            }
            productSets.add(st.pk_invbasdoc);

        }
        
        ///查找价格
        Map<String,Price__c> priceMap = new Map<String,Price__c>();
        for (Price__c p : [select Id ,Taxrate__c,Product__r.pk_invbasdoc__c,Company__c from Price__c 
            where  Product__r.pk_invbasdoc__c in : productSets and Company__c in:corpcodeMap.values()]) {
            
            priceMap.put(p.Company__c +':'+p.Product__r.pk_invbasdoc__c, p);
        }
        System.debug('+++'+priceMap);
        List<Map<String,String>>  pkList = new List<Map<String,String>>();

        ////保存没有匹配到的税率
        List<Map<String,String>>  unMatchList = new List<Map<String,String>>  ();
        ///保存匹配到的价格体系
        List<Price__c> matchedList = new List<Price__c>();
        ///将税率匹配到价格上
        for (SaleRestArgs st : data) {
            if (priceMap.containsKey(corpcodeMap.get(st.unitcode) + ':' + st.pk_invbasdoc)) {
                Price__c p = priceMap.get(corpcodeMap.get(st.unitcode) + ':' + st.pk_invbasdoc);
                p.Taxrate__c = Decimal.valueOf(st.def2);
                matchedList.add(p);
                ///保存pk
                Map<String,String> pk = new Map<String,String>();
                pk.put('mainpk', st.pk_invbasdoc);
                pk.put('sonpk', st.pk_invmandoc);
                pkList.add(pk);
            }else{
                ///保存没有匹配到的产品的pk
                Map<String,String> pk = new Map<String,String>();
                pk.put('mainpk', st.pk_invbasdoc);
                pk.put('sonpk', st.pk_invmandoc);
                unMatchList.add(pk);
            }
        }
        /*
        ///如果没有匹配到价格  则新建价格
        for (Product__c prod: [SELECT Id ,pk_invbasdoc__c FROM Product__c where pk_invbasdoc__c in:unMatchMap.keySet()]) {
            if (unMatchMap.containsKey(prod.pk_invbasdoc__c)) {
                
                Price__c p = new Price__c();
                SaleRestArgs st = unMatchMap.get(prod.pk_invbasdoc__c);
                p.Company__c = corpcodeMap.get(st.unitcode);
                p.Product__c = prod.Id;
                p.Taxrate__c = Decimal.valueOf(st.def2) ;
                pMap.put(prod.pk_invbasdoc__c,p);

                ////保存pk
                Map<String,String> pk = new Map<String,String>();
                pk.put('mainpk', st.pk_invbasdoc);
                pk.put('sonpk', st.pk_invmandoc);
                pkList.add(pk);
            }
        }
        */
        String errpks = unMatchList.size() > 0 ?  JSON.serialize(unMatchList) :'';
        /*
        ////找出没有匹配到价格和产品的pk
        for (SaleRestArgs st : data) {
            if(!pMap.containsKey(st.pk_invbasdoc)){
                errpks += st.pk_invbasdoc +',';
            }
        }*/
        SavePoint sp = Database.setSavePoint();
        try {
            if (matchedList.size() > 0) {
                update matchedList;
            }
          message = Utils.getRestReturnMessage(true,errpks,pkList);
          return message;

        }
        catch (Exception e) {
            Database.rollback(sp);
            message = Utils.getRestReturnMessage(false,e.getMessage()+' : '+e.getStackTraceString(),new List<Map<String ,String>>());
            return message;
        }



    }
    global class SaleRestArgs{
    	global String def2;//税率
        global String pk_invbasdoc;//基本档案pk
        global String unitcode;//公司编码
        global String pk_invmandoc;//管理档案pk 
            
    }
}